package top.zimang.loveforwords.Activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaParser;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.util.List;

import top.zimang.loveforwords.Adapter.AcceptationAdapter;
import top.zimang.loveforwords.Adapter.ExampleSentenceAdapter;
import top.zimang.loveforwords.Base.BaseActivity;
import top.zimang.loveforwords.Model.Word;
import top.zimang.loveforwords.R;
import top.zimang.loveforwords.Service.Mp3Service;
import top.zimang.loveforwords.Service.SearchForWords;

public class DisplayWordActivity extends BaseActivity {
    Word word;
    Mp3Service mp3Service;
    boolean mBound = false;
    BroadcastReceiver mp3Ready=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//                play the mp3
            mp=new MediaPlayer();
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
            File file=null;
            String url=word.getPron().get(0);
            String fileName=url.substring(url.lastIndexOf("/"));
            String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            file=new File(directory+"/loveForWords/pron/"+fileName);
            try{
                mp.reset();
                mp.setDataSource((file.getPath()));
                mp.prepare();
                mp.start();
            }catch(Exception e){e.printStackTrace();}
//            while (mp.isPlaying())
//                Log.i("mp","ok");
        }
    };
    MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word_display);
        word=(Word) getIntent().getExtras().getSerializable("w");

        Intent searchService =new Intent(this, Mp3Service.class);
        bindService(searchService,connection, Context.BIND_AUTO_CREATE);

        ListView listView_A=(ListView) findViewById(R.id.text_wordChinese);
        AppCompatImageView iconChina = (AppCompatImageView) findViewById(R.id.icon_chinese);

        IntentFilter filter=new IntentFilter();
        filter.addAction("mp3Ready");
        registerReceiver(mp3Ready,filter);

        ExampleSentenceAdapter exampleSentenceAdapter=new ExampleSentenceAdapter(
                DisplayWordActivity.this,R.layout.exa_adapter,word.getSent()
        );
        ListView listView_E=(ListView) findViewById(R.id.text_wordSentence);
        listView_E.setAdapter(exampleSentenceAdapter);

        TextView textView=(TextView)findViewById(R.id.text_wordSpelling);
        if (word.getPron().size()==0) {
            LinearLayout layout=(LinearLayout)findViewById(R.id.prons);
            layout.setVisibility(View.GONE);
            listView_A.setVisibility(View.GONE);
            iconChina.setVisibility(View.GONE);
        } else {
            TextView textView2=(TextView)findViewById(R.id.text_wordPhonogramSymbol_UK);
            TextView textView3=(TextView)findViewById(R.id.text_wordPhonogramSymbol_UC);
            AppCompatImageView view_UK_But = (AppCompatImageView) findViewById(R.id.trumpet4UK);
            view_UK_But.setOnClickListener(this::onClick);
            AppCompatImageView view_UC_But = (AppCompatImageView) findViewById(R.id.trumpet4UC);
            view_UC_But.setOnClickListener(this::onClick);
            textView2.setText(word.getPs().get(0));
            textView3.setText(word.getPs().get(1));

            AcceptationAdapter acceptationAdapter=new AcceptationAdapter(
                    DisplayWordActivity.this,R.layout.acceptation_adapter,word.getMeans()
            );
            listView_A.setAdapter(acceptationAdapter);

        }
        textView.setText(word.getKey());



    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.trumpet4UK:
                mp3Service.download(word.getPron().get(0));
                break;
            case R.id.trumpet4UC:
                mp3Service.download(word.getPron().get(1));
                break;
            default:
                break;
        }
    }
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            Mp3Service.MBinder binder = (Mp3Service.MBinder) service;
            mp3Service = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(mp3Ready, new IntentFilter("mp3Ready"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mp3Ready);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mp3Ready);
    }
    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mp3Ready);
    }
}